var express = require('express')
var router = express.Router()
var db = require('../public/javascripts/db')
var util = require('../public/javascripts/utils')
var fs = require('fs')

router.post('/', (req, res, next) => {
    console.log(req.body)
    var data = req.body.info;
    var sql = "UPDATE algorithms SET name = ?,nick = ?,gpu_cpu = ?,output_img = ?,output_args = ?," +
        "language = ?,description = ?,function = ?,modified_time = ? WHERE algorithm_order = ?";
    var sqlParams = [data.name, data.nick, data.gpu_cpu, data.output_img, data.output_args, data.language, data.description, 0, util.getTime(), data.algorithm_order]
    db.query(sql, sqlParams, (err, result) => {
        if (err) {
            throw err
            return
        }
        res.send({msg: 2})
    })
})

router.get('/', (req, res, next) => {
    var sql = 'SELECT * FROM algorithms';
    db.query(sql, (err, result) => {
        if (err) {
            throw err
            return
        }
        res.send({data: result.reverse()})
    })
})

router.put('/', (req, res, next) => {
    console.log(req.body)
    var data = req.body.info;
    var sql = 'UPDATE algorithms SET name = ?,nick = ?,gpu_cpu = ?,output_img = ?,output_args = ?,language = ?,description = ?,function = ?,modified_time = ? WHERE id =?';
    var sqlParams = [data.name, data.nick, data.gpu_cpu, data.output_img, data.output_args, data.language, data.description, data.function, util.getTime(), data.id];
    db.query(sql, sqlParams, (err, result) => {
        if (err) {
            throw err
            return
        }
        res.send({msg: 2})
    })
})

router.delete('/', (req, res, next) => {
    console.log(req.body)
    var sql = "DELETE FROM algorithms WHERE id = ?";
    db.query(sql, req.body.id, (err, result) => {
        if (err) {
            throw err
            return
        }
        deleteall('C:\\Users\\1871518428\\Desktop\\upload\\hadoop')
        res.send({msg: 2})
    })
})

//删除算法文件
function deleteall(path) {
    var files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path)
        files.forEach(function (file, index) {
            var curPath = path + '/' + file
            if (fs.statSync(curPath).isDirectory()) {
                deleteall(curPath)
            } else {
                fs.unlinkSync(curPath)
            }
        })
        fs.rmdirSync(path)
    }
}

module.exports = router